import React, { Component, Fragment } from 'react';
import { formatMessage, FormattedMessage } from 'umi/locale';
import router from 'umi/router';
import {
  Form,
  Input,
  Upload,
  Select,
  Button,
  Rate,
  Row,
  Col,
  message,
  Card,
  Radio,
  Tabs,
} from 'antd';
import { connect } from 'dva';
import styles from './BaseView.less';
import DescriptionList from '@/components/DescriptionList';
import ScrollSelect from '@/components/ScrollSelect';
import get from 'lodash/get';
import isEmpty from 'lodash/isEmpty';
import api from '@/api';
import { REGION_ADDRESS_TYPE, SERVICE_STATUS } from '@/Constants';
import { stringify } from 'querystring';

const { Description } = DescriptionList;

const FormItem = Form.Item;
const { Option } = Select;
const { TabPane } = Tabs;

@connect(({ base, product, loading }) => ({
  currentService: product.currentService,
  scopeRegions: base.scopeRegions,
  loading: loading.effects['base/getRegions'],
  submitting: loading.effects['base/putRegion'],
}))
@Form.create()
class ServiceScopeView extends Component {
  constructor(props) {
    super(props);
    this.state = {
      mode: 'edit',
    };
  }

  componentDidMount() {
    const { dispatch, location, currentService, children } = this.props;
    let isAirline = currentService.typeCode === 'ST004' && currentService.typeCodeSub === 'AIR';
    if (isAirline) {
      dispatch({
        type: 'base/getRegions',
        payload: {
          pathParams: {
            schemaId: currentService.regionStart,
          },
        },
      }).then(res => {
        if (res.errorCode === 0 && res.data && res.data.length > 0) {
          this.setState({ mode: 'view' });
        }
      });
    }
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.currentService !== nextProps.currentService) {
      const { currentService } = nextProps;
      let isAirline = currentService.typeCode === 'ST004' && currentService.typeCodeSub === 'AIR';
      if (isAirline) {
        this.props
          .dispatch({
            type: 'base/getRegions',
            payload: {
              pathParams: {
                schemaId: currentService.regionStart,
              },
            },
          })
          .then(res => {
            if (res.errorCode === 0 && res.data && res.data.length > 0) {
              this.setState({ mode: 'view' });
            }
          });
      }
    }
  }

  handleAddAirline = () => {
    const { dispatch, form, currentService } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      dispatch({
        type: 'base/putRegion',
        payload: {
          pathParams: {
            schemaId: currentService.regionStart,
          },
          data: fieldsValue.airlines.map(item => ({
            areas: [{ code: item.key }],
            regionAddressType: REGION_ADDRESS_TYPE.AIR_LINE,
          })),
        },
      }).then(res => {
        if (res.errorCode === 0) {
          form.resetFields();
          dispatch({
            type: 'base/getRegions',
            payload: {
              pathParams: {
                schemaId: currentService.regionStart,
              },
            },
          }).then(res => {
            if (res.errorCode === 0) {
              this.setState({
                mode: 'view',
              });
              message.success('添加成功');
            }
          });
        }
      });
    });
  };

  handleChangeScope = val => {
    const { currentService, location, match } = this.props;
    router.push(
      `/service/base/${location.query.entry}/create/serviceScope/${val}${location.search}`
    );
  };

  queryAirlines = params => {
    return api.base.queryAirlines({
      queryParams: params,
    });
  };

  renderForm = () => {
    const {
      form: { getFieldDecorator },
      currentService,
      location,
      scopeRegions,
      submitting: submitting,
    } = this.props;
    const { mode } = this.state;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 19 },
      },
    };

    let entry = location.query.entry;
    let editStatus =
      currentService.status === SERVICE_STATUS.DRAFT ||
      (!currentService.isOnline &&
        currentService.status === SERVICE_STATUS.AUDITTED &&
        entry === 'audit');

    return (
      <div>
        <FormItem label="航线" {...formItemLayout}>
          {getFieldDecorator('airlines', {
            rules: [{ required: true, message: '航线不能为空' }],
            initialValue: scopeRegions.map(item => ({
              key: item.areas[0].code,
              label: item.areas[0].name,
            })),
          })(<ScrollSelect style={{ width: 300 }} search={this.queryAirlines} mode="multiple" />)}
        </FormItem>
        <Row type="flex">
          <Col span={5} />
          {editStatus && (
            <Fragment>
              <Button style={{ marginLeft: 50 }} onClick={() => this.setState({ mode: 'view' })}>
                取消
              </Button>
              <Button
                type="primary"
                style={{ marginLeft: 30 }}
                onClick={this.handleAddAirline}
                loading={submitting}
              >
                保存
              </Button>
            </Fragment>
          )}
        </Row>
      </div>
    );
  };

  renderView = () => {
    const { currentService, scopeRegions, location } = this.props;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 19 },
      },
    };

    let entry = location.query.entry;
    let editStatus =
      currentService.status === SERVICE_STATUS.DRAFT ||
      (!currentService.isOnline &&
        currentService.status === SERVICE_STATUS.AUDITTED &&
        entry === 'audit');
    return (
      <div style={{ position: 'relative' }}>
        {editStatus && (
          <Button
            type="primary"
            style={{ position: 'absolute', right: 20, top: 15, zIndex: 2 }}
            onClick={() => this.setState({ mode: 'edit' })}
          >
            编辑
          </Button>
        )}
        <FormItem label="航线" {...formItemLayout}>
          <ul style={{ padding: 0 }}>
            {scopeRegions.map(item => (
              <li>
                {item.areas[0].name}({item.areas[0].code})
              </li>
            ))}
          </ul>
        </FormItem>
      </div>
    );
  };

  render() {
    const { mode } = this.state;
    const { loading, location, currentService, children } = this.props;
    let renderer = null;
    let entry = location.query.entry;
    if (mode == 'edit') renderer = this.renderForm();
    if (mode == 'view') renderer = this.renderView();
    let isAirline = currentService.typeCode === 'ST004' && currentService.typeCodeSub === 'AIR';
    let isOther =
      (currentService.typeCode === 'ST004' && currentService.typeCodeSub === 'OTHER') ||
      currentService.typeCode === 'ST006';
    let activeKey = location.pathname.replace(
      `/service/base/${location.query.entry}/create/serviceScope/`,
      ''
    );
    return (
      <Card bordered={false} loading={loading}>
        {isEmpty(currentService) ? null : children
        /* (
            <Tabs activeKey={activeKey} onChange={this.handleChangeScope}>
              <TabPane tab={isOther ? '起点' : '区域'} key={currentService.regionStart}>
                {children}
              </TabPane>
              {isOther && (
                <TabPane tab="终点" key={currentService.regionEnd}>
                  {children}
                </TabPane>
              )}
            </Tabs>
          ) */
        }
      </Card>
    );
  }
}

export default ServiceScopeView;
